﻿using Hetang.Areas.User.Models.Classes.Config;
using Hetang.Models.Config;
using Hetang.Models.DataContext;
using Hetang.Models.Helper;
using Hetang.Models.Interface;
using Hetang.Models.MailServer;
using Hetang.Models.Repository;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Mail;
using System.Reflection;
using System.Web;

namespace Hetang.Models.MailServer
{
    public class Email
    {
        /// <summary>
        /// 发送邮件（收件人是当前登录用户）
        /// </summary>        
        /// <param name="emailType">操作</param>
        /// <returns></returns>
        public bool SentEmail(EmailType emailType)
        {
            try
            {
                IDatabaseRepository _dr = new DatabaseRepository();
                ISessionRepository _sr = new SessionRepository();
                string chineseEmailType = string.Empty;
                string base64Code = ConvertHelper.GuidToBase64(Guid.NewGuid());

                //插入到数据库
                _dr.InsertEmailCode(new tbl_EmailCode() { Code = base64Code, CreateDate = DateTime.Now, Email = _sr.GetEmail(), HandleType = emailType.ToString(), IP = HttpContext.Current.Request.UserHostAddress, Used = false });

                //初始化邮件服务器
                SmtpClient client = new SmtpClient("smtp.qq.com", 25);
                MailMessage msg = new System.Net.Mail.MailMessage();

                MailServerConfig mailConfig = (MailServerConfig)ConfigurationManager.GetSection("mailServerGroup");

                msg.From = new System.Net.Mail.MailAddress(mailConfig[0].UserName, WebConfig.WebsiteName);                    

                //读取模板
                string content = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/Views/Shared/EmailLayout/Global.html"));                

                switch (emailType)
                {
                    case EmailType.Register:
                        chineseEmailType = "注册新用户";
                        break;
                    case EmailType.ResetPassword:
                        chineseEmailType = "重置密码";
                        break;
                    default:
                        chineseEmailType = "未知操作";
                        break;
                }

                msg.To.Add(_dr.GetEmail());
                msg.Subject = chineseEmailType + " - " + WebConfig.WebsiteName + " （系统邮件）";

                content = content.Replace("$UserName", _sr.GetUserName()).Replace("$WebSiteName", WebConfig.WebsiteName).Replace("$Control", chineseEmailType).Replace("$Link", WebConfig.SiteHost + "user/changepwd?code=" + base64Code).Replace("$WebSiteHost", WebConfig.SiteHost);

                msg.Body = content;
                msg.BodyEncoding = System.Text.Encoding.UTF8;
                msg.IsBodyHtml = true;
                client.UseDefaultCredentials = false;
                System.Net.NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential(mailConfig[0].UserName, mailConfig[0].Password);
                client.Credentials = basicAuthenticationInfo;
                client.EnableSsl = false;
                client.Send(msg);

                HttpCookie cookie = new HttpCookie("resetpwd", HttpContext.Current.Server.UrlEncode(DateTime.Now.ToString()));
                cookie.Expires = DateTime.Now.AddMinutes(mailConfig[0].ExpiresMinute);
                HttpContext.Current.Response.Cookies.Add(cookie);

                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}